package com.xywh.wanandroid.compose_ui.main.bottomBar

import android.text.Html
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.consumeWindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.material3.Divider
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SecondaryScrollableTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRowDefaults
import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import com.xywh.composeLibrary.ext.ListFloatingActionButton
import com.xywh.composeLibrary.statex.StateCompose
import com.xywh.wanandroid.compose_ui.main.cancelOrAddCollectArticle
import com.xywh.wanandroid.data.model.bean.ArticleItem
import com.xywh.wanandroid.data.model.bean.ProjectTreeItem
import com.xywh.wanandroid.event.EventViewModel
import com.xywh.wanandroid.ext.showToastMsg
import com.xywh.wanandroid.viewmodel.MainComposeViewModel
import com.zj.banner.utils.ImageLoader


@Composable
fun ProjectScreen(
    mainComposeViewModel: MainComposeViewModel,
    innerPadding: PaddingValues,
    navigateWebView: (String, String) -> Unit
) {

    val projectTree =
        mainComposeViewModel.projectTree.collectAsLazyPagingItems()


    StateCompose(projectTree) {

        val projectArticles =
            mainComposeViewModel.projectArticles.value?.collectAsLazyPagingItems()

        mainComposeViewModel.collectProjectArticlesLiveData.collectAsState(initial = "")

        projectTree[0]?.let {

            if (mainComposeViewModel.projectId == 0) {
                mainComposeViewModel.projectId = it.id
                mainComposeViewModel.getProjectArticles()
            }
        }
        ProjectContent(
            innerPadding,
            projectTree,
            projectArticles,
            favoriteOnClick = { id, collect ->
                cancelOrAddCollectArticle(collect, mainComposeViewModel, id)
            },
            navigateWebView = navigateWebView
        ) {

            mainComposeViewModel.projectId = it
            mainComposeViewModel.getProjectArticles()
        }
    }
}


@Composable
@OptIn(ExperimentalMaterialApi::class, ExperimentalFoundationApi::class)
fun ProjectContent(
    innerPadding: PaddingValues,
    projectTree: LazyPagingItems<ProjectTreeItem>?,
    projectArticles: LazyPagingItems<ArticleItem>?,
    navigateWebView: (String, String) -> Unit,
    favoriteOnClick: (Int, Boolean) -> Unit,
    tabOnclick: (Int) -> Unit
) {

    val refresh by remember { mutableStateOf(false) }
    val pullRefreshState = rememberPullRefreshState(refresh, {
        projectArticles?.refresh()
    })


    Box(
        modifier = Modifier
            .fillMaxSize()
            .pullRefresh(pullRefreshState)
    ) {

        val listState = rememberLazyListState()



        Column(Modifier.fillMaxSize()) {
            var state by rememberSaveable { mutableIntStateOf(0) }

            projectTree?.let {

                if (it.itemCount > 0) {
                    SecondaryScrollableTabRow(
                        modifier = Modifier
//                                .padding(top = innerPadding.calculateTopPadding())
                            .fillMaxWidth(),
                        selectedTabIndex = state,
                        containerColor = MaterialTheme.colorScheme.primary,
                        contentColor = Color.White,
                        edgePadding = 0.dp,
                        divider = { HorizontalDivider(color = Color.Transparent) },
                        indicator = { tabPositions ->
                            TabRowDefaults.SecondaryIndicator(
                                Modifier.tabIndicatorOffset(tabPositions[state]),
                                color = Color.White
                            )
                        }
                    ) {
                        it.let { projectTree ->

                            projectTree.itemSnapshotList.forEachIndexed { index, projectTreeItem ->
                                Tab(
                                    selected = state == index,
                                    onClick = {
                                        state = index
                                        if (projectTreeItem != null) {
                                            tabOnclick.invoke(projectTreeItem.id)
                                        }
                                    },
                                    text = {

                                        val fontWeight = if (state == index) {
                                            FontWeight.Bold
                                        } else {
                                            FontWeight.Normal
                                        }
                                        if (projectTreeItem != null) {
                                            Text(
                                                Html.fromHtml(projectTreeItem.name)
                                                    .toString(),
                                                fontWeight = fontWeight
                                            )
                                        }

                                    }
                                )
                            }
                        }
                    }
                }
            }


            LazyColumn(
                state = listState,
                // consume insets as scaffold doesn't do it by default
                modifier = Modifier
                    .consumeWindowInsets(innerPadding),
//            contentPadding = innerPadding,
            ) {

                projectArticles?.let {
                    items(
                        count = projectArticles.itemCount,
                        key = { index ->
                            val article = projectArticles[index]
                            "${article?.id ?: ""}${index}"
                        }) {
                        val itemData = projectArticles[it] ?: return@items
                        ProjectArticle(itemData, favoriteOnClick = favoriteOnClick) { title, link ->
                            navigateWebView.invoke(title, link)
                        }
                    }
                }

            }

        }
        Box(
            Modifier
                .padding(10.dp)
                .align(Alignment.BottomEnd)
        ) {
            ListFloatingActionButton(rememberCoroutineScope(), listState)
        }
        PullRefreshIndicator(
            refresh,
            pullRefreshState,
            Modifier.align(Alignment.TopCenter),
            scale = true
        )
    }
}

@Composable
fun ProjectArticle(
    itemArticle: ArticleItem,
    favoriteOnClick: (Int, Boolean) -> Unit,
    itemOnClick: (title: String, link: String) -> Unit
) {
    ListItem(
        modifier = Modifier.clickable {
            itemOnClick.invoke(itemArticle.title, itemArticle.link)
        },
        headlineContent = {
            Text(
                itemArticle.desc,
                fontSize = 12.sp,
                color = Color.Gray,
                modifier = Modifier
                    .padding(top = 5.dp)
                    .fillMaxWidth(),
                maxLines = 3, overflow = TextOverflow.Ellipsis
            )
        },
        overlineContent = {
            Text(
                itemArticle.title,
                fontSize = 14.sp,
                color = Color.Black,
                modifier = Modifier
                    .fillMaxWidth(),
                maxLines = 1, overflow = TextOverflow.Ellipsis
            )
        },
        supportingContent = {
            Column(Modifier.fillMaxWidth()) {


                Row(Modifier.fillMaxWidth()) {

                    Text(
                        itemArticle.author.ifEmpty { itemArticle.shareUser },
                        fontSize = 12.sp,
                        color = Color(0xFF747474),
                        modifier = Modifier
                            .align(Alignment.Bottom)
                    )

                    Text(
                        itemArticle.niceDate ?: "",
                        fontSize = 12.sp,
                        color = Color(0xFF747474),
                        modifier = Modifier
                            .padding(start = 5.dp)
                            .fillMaxWidth()
                            .align(Alignment.Bottom),
                        textAlign = TextAlign.End
                    )
                }
                Row(
                    Modifier
                        .padding(top = 5.dp)
                        .fillMaxWidth(),
                    horizontalArrangement = Arrangement.End
                ) {
                    var favorite = Icons.Filled.FavoriteBorder

                    if (itemArticle.collect) {
                        favorite = Icons.Filled.Favorite
                    }

                    Icon(
                        imageVector = favorite,
                        modifier = Modifier
                            .size(18.dp)
                            .clickable {
                                if (EventViewModel.isLogin.value) {
                                    val collect = itemArticle.collect
                                    itemArticle.collect = !itemArticle.collect
                                    favoriteOnClick.invoke(itemArticle.id, collect)
                                } else {
                                    showToastMsg("请先登录")
                                }

                            },
                        contentDescription = "Localized description",
                    )
                }
            }
        },
        leadingContent = {
            ImageLoader(
                data = itemArticle.envelopePic,
                modifier = Modifier
                    .width(80.dp)
                    .height(140.dp),
                contentScale = ContentScale.FillHeight
            )
        },
        //                        trailingContent = {
        //
        //                        }
    )
    Divider()
}
